package com.zxkj.commonpatrol.ui;

import androidx.annotation.RequiresApi;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import com.czy.basecommon.utils.base.BaseVmDataBindingActivity;
import com.czy.basecommon.utils.tools.ActivityTool;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luck.picture.lib.PhotoEditorActivity;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.model.EditPicEvent;
import com.luck.picture.lib.tools.SdkVersionUtils;
import com.xuexiang.xui.widget.toast.XToast;
import com.zxkj.commonpatrol.BR;
import com.zxkj.commonpatrol.R;
import com.zxkj.commonpatrol.adapt.MediaAdapt;
import com.zxkj.commonpatrol.adapt.MyTextSimpleAdapter;

import com.zxkj.commonpatrol.databinding.ActivityPatrolSetRequestBinding;
import com.zxkj.commonpatrol.model.entity.Group;
import com.zxkj.commonpatrol.model.entity.MyMediaEntry;
import com.zxkj.commonpatrol.model.entity.itemPicEntity;
import com.zxkj.commonpatrol.model.entity.itemVideoEntity;
import com.zxkj.commonpatrol.model.entity.itemVioceEntity;
import com.zxkj.commonpatrol.utils.AudioRecorderButton;
import com.zxkj.commonpatrol.utils.VideoRecordActivity;
import com.zxkj.commonpatrol.viewmodel.PatrolSetQuestViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class PatrolSetQuestActivity extends BaseVmDataBindingActivity<ActivityPatrolSetRequestBinding, PatrolSetQuestViewModel> {

    private MediaAdapt myMediaAdapt1;
    private MediaAdapt myMediaAdapt2;
    private MediaAdapt myMediaAdapt3;
    private static final int REQUEST_VIDEO = 99;
    private static final int REQUEST_VIDEO2 = 100;
    private static final int REQUEST_VIDEO3 = 101;

    private List<LocalMedia> selectListData1 = new ArrayList<>();//group1
    private List<LocalMedia> selectListData2 = new ArrayList<>();//group2
    private List<LocalMedia> selectListData3 = new ArrayList<>();//group3
    private MyTextSimpleAdapter simpleAdapter;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_patrol_set_request;
    }

    @Override
    public int initVariableId() {
        return BR.mPatrolListViewModel;
    }



    @Override
    protected void initUI() {
        boolean b = SdkVersionUtils.checkedAndroid_Q();
          EventBus.getDefault().register(this);
        //初始化recyleview
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.recyGroup1Pic.setLayoutManager(layoutManager1);

        LinearLayoutManager layoutManager2 = new LinearLayoutManager(this);
        layoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.recyGroup2Pic.setLayoutManager(layoutManager2);


        LinearLayoutManager layoutManager3 = new LinearLayoutManager(this);
        layoutManager3.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.recyGroup3Pic.setLayoutManager(layoutManager3);

        myMediaAdapt1 = new MediaAdapt(getSupportFragmentManager(),1,this);//第一組
        binding.recyGroup1Pic.setAdapter(myMediaAdapt1);


        myMediaAdapt2 = new MediaAdapt(getSupportFragmentManager(),2,this);//第二組
        binding.recyGroup2Pic.setAdapter(myMediaAdapt2);


        myMediaAdapt3 = new MediaAdapt(getSupportFragmentManager(),3,this);//第三組
        binding.recyGroup3Pic.setAdapter(myMediaAdapt3);
        binding.llGroup2.setVisibility(View.GONE);
        binding.llGroup3.setVisibility(View.GONE);
        binding.btnClear.setClickable(false);
        binding.btnClear.setEnabled(false);
        binding.btnClear.setBackgroundColor(Color.parseColor("#D2D2D2"));

        binding.btnSubmit.setClickable(false);
        binding.btnSubmit.setEnabled(false);
        binding.btnSubmit.setBackgroundColor(Color.parseColor("#D2D2D2"));

        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        binding.recyContent.setLayoutManager(linearLayoutManager);

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void setListener() {
        super.setListener();
        //第一组语音回调
        binding.addVo.setAudioFinishRecorderListener((seconds, filePath) -> {
            myMediaAdapt1.addData(new MyMediaEntry(2,new itemVioceEntity(0,filePath),null,null));
            long counts = myMediaAdapt1.getData().stream().filter(p -> p.getVioceEntity() != null).map(p -> p.getVioceEntity()).count();
            int count = Integer.parseInt(String.valueOf(counts));
            binding.addVo.setCountss(count);
        });
        //第二组语音回调
        binding.addVo2.setAudioFinishRecorderListener((seconds, filePath) -> {
            myMediaAdapt2.addData(new MyMediaEntry(2,new itemVioceEntity(0,filePath),null,null));
            long counts = myMediaAdapt2.getData().stream().filter(p -> p.getVioceEntity() != null).map(p -> p.getVioceEntity()).count();
            int count = Integer.parseInt(String.valueOf(counts));
            binding.addVo2.setCountss(count);
        });
        //第三组语音回调
        binding.addVo3.setAudioFinishRecorderListener((seconds, filePath) -> {
            myMediaAdapt3.addData(new MyMediaEntry(2,new itemVioceEntity(0,filePath),null,null));
            long counts = myMediaAdapt3.getData().stream().filter(p -> p.getVioceEntity() != null).map(p -> p.getVioceEntity()).count();
            int count = Integer.parseInt(String.valueOf(counts));
            binding. addVo3.setCountss(count);
        });

        binding.ivAddPo.setOnClickListener(v->{
            addPic(myMediaAdapt1, PictureConfig.CHOOSE_REQUEST1);

        });
        binding.ivAddPo2.setOnClickListener(v->{
            addPic(myMediaAdapt2,PictureConfig.CHOOSE_REQUEST2);

        });
        binding.ivAddPo3.setOnClickListener(v->{
            addPic(myMediaAdapt3,PictureConfig.CHOOSE_REQUEST3);

        });
        binding.addVe.setOnClickListener(v->{
            addVideo(myMediaAdapt1,REQUEST_VIDEO);

        });
        binding.addVe2.setOnClickListener(v->{
            addVideo(myMediaAdapt2,REQUEST_VIDEO2);


        });

        binding.addVe3.setOnClickListener(v->{
            addVideo(myMediaAdapt3,REQUEST_VIDEO3);



        });

        binding.ivDeleteGroup2.setOnClickListener(v->{
            binding.llGroup2.setVisibility(View.GONE);
            binding.ivAddGroup.setVisibility(View.VISIBLE);
            myMediaAdapt2.getData().clear();
            myMediaAdapt2.MyNotifyDataSetChanged();


        });

        binding.ivDeleteGroup3.setOnClickListener(v->{
            binding.ivAddGroup.setVisibility(View.VISIBLE);
            binding.llGroup3.setVisibility(View.GONE);
            myMediaAdapt3.getData().clear();
            myMediaAdapt3.MyNotifyDataSetChanged();


        });

        binding.ivAddGroup.setOnClickListener(v->{
            if( binding.llGroup3.getVisibility()==View.VISIBLE&& binding.llGroup2.getVisibility()==View.GONE){
                binding. llGroup2.setVisibility(View.VISIBLE);
                binding. ivAddGroup.setVisibility(View.GONE);
            }else if ( binding.llGroup3.getVisibility()==View.GONE&& binding.llGroup2.getVisibility()==View.VISIBLE){
                binding. llGroup3.setVisibility(View.VISIBLE);
                binding.ivAddGroup.setVisibility(View.GONE);
            }else if( binding.llGroup3.getVisibility()==View.GONE&& binding.llGroup2.getVisibility()==View.GONE){
                binding.llGroup2.setVisibility(View.VISIBLE);
            }

        });

        binding.ivAdd.setOnClickListener(v->{
            startActivity(NewExceptionActivity.class);
        });
        binding.btnSubmit.setOnClickListener(v->{
            startActivity(ProblemListActivity.class);
            ActivityTool.getInstance().popOneActivity(this);
        });


    }
    private void setImage(int x) {

        PictureSelector.create(PatrolSetQuestActivity.this)// 是否可预览图片 true or false
                .openCamera(PictureMimeType.ofImage())
                .compress(true)
                .forResult(x);

    }
    @Override
    protected void initData() {
      //初始化数据
        List<Group> groups=new ArrayList<>();

        Group group =new Group();

        group.setTitle("機房設備不穩定");
        group.setTYPE(1);
        groups.add(group);
         simpleAdapter =new MyTextSimpleAdapter( binding.recyContent,groups,this);
        binding.recyContent.setAdapter(simpleAdapter);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST1:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia1 = selectList.get(0);
                    selectListData1.add(localMedia1);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    for (LocalMedia bean : selectList) {
                        String compressPath = bean.getCompressPath();

                        if (selectListData1.size() == 3) {

                        } else {

                        }

                        Intent intent = new Intent(PatrolSetQuestActivity.this, PhotoEditorActivity.class);
                        intent.putExtra("paths", compressPath);
                        intent.putExtra("type", PictureConfig.CHOOSE_REQUEST1);
                        startActivity(intent);

                    }
                    break;
                case PictureConfig.CHOOSE_REQUEST2:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList1 = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia2 = selectList1.get(0);
                    selectListData2.add(localMedia2);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    for (LocalMedia bean : selectList1) {
                        String compressPath = bean.getCompressPath();

                        if (selectListData2.size() == 3) {

                        } else {

                        }

                        Intent intent = new Intent(PatrolSetQuestActivity.this, PhotoEditorActivity.class);
                        intent.putExtra("paths", compressPath);
                        intent.putExtra("type", PictureConfig.CHOOSE_REQUEST2);
                        startActivity(intent);

                    }
                    break;
                case PictureConfig.CHOOSE_REQUEST3:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList2 = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia3 = selectList2.get(0);
                    selectListData3.add(localMedia3);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    for (LocalMedia bean : selectList2) {
                        String compressPath = bean.getCompressPath();

                        if (selectListData3.size() == 3) {

                        } else {

                        }

                        Intent intent = new Intent(PatrolSetQuestActivity.this, PhotoEditorActivity.class);
                        intent.putExtra("paths", compressPath);
                        intent.putExtra("type", PictureConfig.CHOOSE_REQUEST3);
                        startActivity(intent);

                    }
                    break;
                case REQUEST_VIDEO:

                    String path = data.getStringExtra("path");
                    String imgPath = data.getStringExtra("imagePath");
                    int type = data.getIntExtra("type", -1);
                    if (type == 0) {
                        myMediaAdapt1.addData(new MyMediaEntry(3, null, null, new itemVideoEntity(path, imgPath)));
                    }
                    break;

                case REQUEST_VIDEO2:
                    String path2 = data.getStringExtra("path");
                    String imgPath2 = data.getStringExtra("imagePath");
                    int type2 = data.getIntExtra("type", -1);
                    if (type2 == 0) {
                        myMediaAdapt2.addData(new MyMediaEntry(3, null, null, new itemVideoEntity(path2, imgPath2)));
                    }
                    break;

                case REQUEST_VIDEO3:
                    String path3 = data.getStringExtra("path");
                    String imgPath3 = data.getStringExtra("imagePath");
                    int type3 = data.getIntExtra("type", -1);
                    if (type3 == 0) {
                        myMediaAdapt3.addData(new MyMediaEntry(3, null, null, new itemVideoEntity(path3, imgPath3)));
                    }
                    break;


            }
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        File file = new File(ETFConstant.VIOCEPATH);
//        FileHelper.deleteFile(file);
        EventBus.getDefault().unregister(this);

    }
    public AudioRecorderButton getGroup1MyAudioRecorderButton(){

        return   binding.addVo;

    }
    public AudioRecorderButton getGroup2MyAudioRecorderButton(){

        return    binding.addVo2;

    }
    public AudioRecorderButton getGroup3MyAudioRecorderButton(){

        return    binding.addVo3;

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEditPic(EditPicEvent editEvent) {
        if (editEvent.isIsok()) {
            switch (editEvent.getIvType()) {
                case PictureConfig.CHOOSE_REQUEST1:
                    myMediaAdapt1.addData(new MyMediaEntry(1, null, new itemPicEntity(editEvent.getPath()), null));

                    break;
                case PictureConfig.CHOOSE_REQUEST2:
                    myMediaAdapt2.addData(new MyMediaEntry(1, null, new itemPicEntity(editEvent.getPath()), null));

                    break;
                case PictureConfig.CHOOSE_REQUEST3:
                    myMediaAdapt3.addData(new MyMediaEntry(1, null, new itemPicEntity(editEvent.getPath()), null));

                    break;
            }
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void addVideo(MediaAdapt adapt,int i) {
        long counts = adapt.getData().stream().filter(p -> p.getItemVideoEntity() != null).map(p -> p.getItemVideoEntity()).count();
        int count = Integer.parseInt(String.valueOf(counts));
        if (count==1){
            XToast.error(PatrolSetQuestActivity.this, "添加視頻超過最大數量").show();
        }else{
            //
            Intent intent = new Intent();
            intent.setClass(PatrolSetQuestActivity.this, VideoRecordActivity.class);

            startActivityForResult(intent, i);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void addPic(MediaAdapt adapt,int i) {
        long counts = adapt.getData().stream().filter(p -> p.getItemPicEntity() != null).map(p -> p.getItemPicEntity()).count();
        int count = Integer.parseInt(String.valueOf(counts));
        if (count == 1) {
            XToast.error(PatrolSetQuestActivity.this, "添加圖片超過最大數量").show();
        } else {
            setImage(i);

        }
    }


    @Override
    protected void dataObserver() {
        super.dataObserver();

        LiveEventBus.get("isClick",Boolean.class).observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean){

                    binding.btnClear.setClickable(true);
                    binding.btnClear.setEnabled(true);
                    binding.btnClear.setBackgroundColor(getColor(R.color.login_btn));

                    binding.btnSubmit.setClickable(true);
                    binding.btnSubmit.setEnabled(true);
                    binding.btnSubmit.setBackgroundColor(getColor(R.color.login_btn));
                }
            }
        });



        LiveEventBus.get("cs", Group.class).observe(this, new Observer<Group>() {
            @Override
            public void onChanged(Group s) {
                List<Group> groups = new ArrayList<>();
                groups.add(s);
                simpleAdapter.addData(0,groups.get(0));


            }
        });

    }
}
